import os, sys
import json
from glob import glob

def loadjson2xy_list(json_file):
    x_list = []
    y_list = []
    h = 0
    w = 0
    try:
        file_object = open(json_file)
        all_the_text = file_object.read()
        attr_root = json.loads(all_the_text)
        for shape in attr_root['shapes']:
            for p in shape['points']:
                y = p[1]
                x = p[0]
                x_list.append(int(x))
                y_list.append(int(y))
        h = attr_root['imageHeight']
        w = attr_root['imageWidth']
    except Exception as ex:
        print("load json 2 xy exception:" + str(ex))
    return x_list, y_list, w, h


def convt2ratio(p_list_x, plist_y, w, h):
    p_list_x = [i / w for i in p_list_x]
    plist_y = [i / h for i in plist_y]
    return p_list_x, plist_y


def serialise2txt(p_list_x, p_list_y, txt_path):
    with open(txt_path, 'w') as f:
        f.write('4,')
        for x in p_list_x:
            f.write("{:.6f}".format(x))
            f.write(',')
        for y in p_list_y:
            f.write("{:.6f}".format(y))
            f.write(',')
        f.write(',')


def gen_one(json_file, txt_out):
    x_list, y_list, w, h = loadjson2xy_list(json_file)
    if w != 0 and h != 0:
        x_list, y_list = convt2ratio(x_list, y_list, w, h)
        serialise2txt(x_list, y_list, txt_out)


def case2(dir = './anno_eg/'):
    annos = glob('{}/*.json'.format(dir))
    for anno in annos:
        gen_one(anno,os.path.splitext(anno)[0]+'.txt')

if __name__ == '__main__':
    # case2(dir = './anno_eg')
    case2(dir='/home/leo/Downloads/datas/gen_wpod_det_trainset/road_gate_pl/nee_anno')